/**
 * 场景树 UI 管理器
 * 负责将 SceneTreeManager 的数据渲染为树形UI
 * 处理用户交互（展开/折叠、选择、可见性切换等）
 */

import * as THREE from 'three';

export class SceneTreeUI {
    constructor(containerElement, treeManager, mode = 'edit') {
        this.container = containerElement;
        this.treeManager = treeManager;
        this.expandedNodes = new Set(['root']); // 展开的节点ID集合
        this.mode = mode; // 'edit' 或 'presentation'
        
        // 拖拽相关状态
        this.draggedNode = null;
        this.dropTarget = null;
        this.dragPlaceholder = null;
        
        // 场景树逐层展开层级计数器
        this.sceneTreeExpandLevel = 0;
        
        // 绑定事件
        this.setupEventListeners();
        
        console.log(`✅ 场景树UI已初始化 (模式: ${mode})`);
    }
    
    /**
     * 设置事件监听
     */
    setupEventListeners() {
        // 监听树管理器的事件
        this.treeManager.on('nodeAdded', () => this.refresh());
        this.treeManager.on('nodeRemoved', () => this.refresh());
        this.treeManager.on('nodeMoved', () => this.refresh());
        this.treeManager.on('nodeSelected', ({ node }) => this.highlightNode(node.id));
    }
    
    /**
     * 渲染整个树
     */
    render() {
        this.container.innerHTML = '';
        
        const rootNode = this.treeManager.root;
        
        if (!rootNode || rootNode.children.length === 0) {
            this.renderEmpty();
            return;
        }
        
        // 渲染根节点的所有子节点
        const treeElement = document.createElement('div');
        treeElement.className = 'tree-root';
        
        rootNode.children.forEach(child => {
            const nodeElement = this.renderNode(child);
            treeElement.appendChild(nodeElement);
        });
        
        this.container.appendChild(treeElement);
        
        console.log(`🌲 场景树已渲染，共 ${this.treeManager.getNodeCount()} 个节点`);
    }
    
    /**
     * 渲染单个节点
     */
    renderNode(node, level = 0) {
        const nodeElement = document.createElement('div');
        nodeElement.className = 'tree-node';
        nodeElement.dataset.nodeId = node.id;
        nodeElement.dataset.level = level;
        
        // 节点内容
        const contentElement = document.createElement('div');
        contentElement.className = 'tree-node-content';
        if (node.visible) contentElement.classList.add('visible');
        if (this.treeManager.selectedNode?.id === node.id) {
            contentElement.classList.add('selected');
        }
        
        // 编辑模式下启用拖拽功能
        if (this.mode === 'edit' && node.id !== 'root') {
            contentElement.draggable = true;
            this.setupDragEvents(contentElement, node);
        }
        
        // 缩进
        contentElement.style.paddingLeft = `${level * 20 + 10}px`;
        
        // 展开/折叠按钮
        const toggleElement = document.createElement('div');
        toggleElement.className = 'tree-node-toggle';
        if (node.children.length === 0) {
            toggleElement.classList.add('empty');
        } else if (this.expandedNodes.has(node.id)) {
            toggleElement.classList.add('expanded');
            toggleElement.textContent = '▶';
        } else {
            toggleElement.textContent = '▶';
        }
        toggleElement.onclick = (e) => {
            e.stopPropagation();
            this.toggleNode(node.id);
        };
        
        // 节点图标
        const iconElement = document.createElement('div');
        iconElement.className = 'tree-node-icon';
        iconElement.dataset.type = node.type;
        
        // 节点名称
        const nameElement = document.createElement('div');
        nameElement.className = 'tree-node-name';
        nameElement.textContent = node.name;
        nameElement.title = node.getPath();
        
        // 节点操作按钮（根据模式显示）
        const actionsElement = document.createElement('div');
        actionsElement.className = 'tree-node-actions';
        
        // 编辑模式：显示所有操作按钮
        if (this.mode === 'edit') {
            // 添加子节点按钮
            const addChildBtn = document.createElement('button');
            addChildBtn.className = 'tree-node-action-btn tree-node-add-child';
            addChildBtn.textContent = '➕';
            addChildBtn.title = '添加子节点';
            addChildBtn.onclick = (e) => {
                e.stopPropagation();
                this.addChildNode(node.id);
            };
            actionsElement.appendChild(addChildBtn);
            
            // 可见性按钮
            const visibleBtn = document.createElement('button');
            visibleBtn.className = 'tree-node-action-btn tree-node-visible';
            visibleBtn.textContent = node.visible ? '👁' : '👁‍🗨';
            visibleBtn.title = node.visible ? '隐藏' : '显示';
            visibleBtn.onclick = (e) => {
                e.stopPropagation();
                this.toggleVisibility(node.id);
            };
            actionsElement.appendChild(visibleBtn);
            
            // 锁定按钮
            if (node.locked) {
                const lockedBtn = document.createElement('button');
                lockedBtn.className = 'tree-node-action-btn tree-node-locked';
                lockedBtn.textContent = '🔒';
                lockedBtn.title = '已锁定';
                actionsElement.appendChild(lockedBtn);
            }
            
            // 删除按钮
            if (node.id !== 'root') {
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'tree-node-action-btn';
                deleteBtn.textContent = '🗑';
                deleteBtn.title = '删除';
                deleteBtn.onclick = (e) => {
                    e.stopPropagation();
                    this.deleteNode(node.id);
                };
                actionsElement.appendChild(deleteBtn);
            }
        }
        // 演示模式：不显示任何操作按钮
        // 在演示模式下，用户只能浏览，不能编辑
        
        // 组装节点内容
        contentElement.appendChild(toggleElement);
        contentElement.appendChild(iconElement);
        contentElement.appendChild(nameElement);
        contentElement.appendChild(actionsElement);
        
        // 节点点击事件
        contentElement.onclick = () => {
            this.selectNode(node.id);
        };
        
        nodeElement.appendChild(contentElement);
        
        // 子节点容器
        if (node.children.length > 0) {
            const childrenElement = document.createElement('div');
            childrenElement.className = 'tree-node-children';
            if (this.expandedNodes.has(node.id)) {
                childrenElement.classList.add('expanded');
            }
            
            node.children.forEach(child => {
                const childElement = this.renderNode(child, level + 1);
                childrenElement.appendChild(childElement);
            });
            
            nodeElement.appendChild(childrenElement);
        }
        
        return nodeElement;
    }
    
    /**
     * 渲染空状态
     */
    renderEmpty() {
        this.container.innerHTML = `
            <div class="tree-empty">
                <div class="tree-empty-icon">🌲</div>
                <div>场景树为空</div>
                <div style="font-size: 11px; margin-top: 8px; opacity: 0.6;">
                    拖拽模型到场景中添加对象
                </div>
            </div>
        `;
    }
    
    /**
     * 展开/折叠节点
     */
    toggleNode(nodeId) {
        if (this.expandedNodes.has(nodeId)) {
            this.expandedNodes.delete(nodeId);
        } else {
            this.expandedNodes.add(nodeId);
        }
        this.render();
    }
    
    /**
     * 选择节点
     */
    selectNode(nodeId) {
        this.treeManager.selectNode(nodeId);
        this.highlightNode(nodeId);
        
        console.log(`📍 选中节点: ${nodeId}`);
    }
    
    /**
     * 高亮显示选中的节点
     */
    highlightNode(nodeId) {
        // 移除所有选中状态
        this.container.querySelectorAll('.tree-node-content.selected').forEach(el => {
            el.classList.remove('selected');
        });
        
        // 添加选中状态
        const nodeElement = this.container.querySelector(`[data-node-id="${nodeId}"] > .tree-node-content`);
        if (nodeElement) {
            nodeElement.classList.add('selected');
            nodeElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }
    
    /**
     * 切换节点可见性
     */
    toggleVisibility(nodeId) {
        const node = this.treeManager.findNodeById(nodeId);
        if (node) {
            node.toggleVisible();
            this.render();
            console.log(`👁 节点 "${node.name}" 可见性: ${node.visible}`);
            
            // 立即通知后端保存
            this.notifyTreeChanged();
        }
    }
    
    /**
     * 删除节点
     */
    deleteNode(nodeId) {
        const node = this.treeManager.findNodeById(nodeId);
        if (!node) return;
        
        if (confirm(`确定要删除节点 "${node.name}" 及其所有子节点吗？`)) {
            this.treeManager.removeNode(nodeId);
            this.render();
            console.log(`🗑 已删除节点: ${node.name}`);
            
            // 立即通知后端保存
            this.notifyTreeChanged();
        }
    }
    
    /**
     * 逐层展开节点
     */
    expandAll() {
        // 增加展开层级
        this.sceneTreeExpandLevel++;
        
        // 清空展开节点集合（除了根节点）
        this.expandedNodes.clear();
        this.expandedNodes.add('root'); // 保持根节点展开
        
        // 递归函数：展开到指定层级
        const expandToLevel = (node, currentLevel) => {
            if (currentLevel < this.sceneTreeExpandLevel && node.children.length > 0) {
                // 当前层级小于目标层级，展开
                this.expandedNodes.add(node.id);
                // 递归处理子节点
                node.children.forEach(child => {
                    expandToLevel(child, currentLevel + 1);
                });
            }
            // 如果当前层级等于或大于目标层级，不展开（不添加到expandedNodes中）
        };
        
        // 从根节点的子节点开始（level 0）
        if (this.treeManager.root) {
            this.treeManager.root.children.forEach(child => {
                expandToLevel(child, 0);
            });
        }
        
        this.render();
    }
    
    /**
     * 折叠所有节点
     */
    collapseAll() {
        // 重置展开层级计数器
        this.sceneTreeExpandLevel = 0;
        
        this.expandedNodes.clear();
        this.expandedNodes.add('root'); // 保持根节点展开
        this.render();
    }
    
    /**
     * 设置显示模式
     * @param {string} mode - 'edit' 或 'presentation'
     */
    setMode(mode) {
        if (mode !== 'edit' && mode !== 'presentation') {
            console.error('❌ 无效的模式:', mode);
            return;
        }
        
        this.mode = mode;
        this.render();
        
        // 更新面板头部工具栏按钮显示
        this.updateHeaderButtons();
        
        console.log(`🔄 场景树模式已切换: ${mode === 'edit' ? '编辑模式' : '演示模式'}`);
    }
    
    /**
     * 更新面板头部按钮显示
     */
    updateHeaderButtons() {
        const panel = this.container.closest('.side-panel');
        if (!panel) return;
        
        // 根据模式显示/隐藏编辑功能按钮
        const editOnlyButtons = panel.querySelectorAll('.edit-only');
        editOnlyButtons.forEach(btn => {
            if (this.mode === 'presentation') {
                btn.style.display = 'none';
            } else {
                btn.style.display = '';
            }
        });
    }
    
    /**
     * 刷新树显示
     */
    refresh() {
        this.render();
    }
    
    /**
     * 显示加载状态
     */
    showLoading() {
        this.container.innerHTML = '<div class="tree-loading">加载中...</div>';
    }
    
    /**
     * 从JSON数据加载树
     */
    loadFromJSON(treeData) {
        // 重置场景树展开层级计数器
        this.sceneTreeExpandLevel = 0;
        
        this.treeManager.fromJSON(treeData);
        this.render();
    }
    
    /**
     * 导出树为JSON
     */
    toJSON() {
        return this.treeManager.toJSON();
    }
    
    /**
     * 通知场景树发生变化，触发保存
     */
    notifyTreeChanged() {
        // 触发自定义事件，通知 app.js 保存场景树
        const event = new CustomEvent('sceneTreeChanged');
        window.dispatchEvent(event);
    }
    
    /**
     * 设置节点的拖拽事件
     */
    setupDragEvents(element, node) {
        // 拖拽开始
        element.addEventListener('dragstart', (e) => {
            this.draggedNode = node;
            element.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', node.id);
            console.log(`🎯 开始拖拽节点: ${node.name}`);
        });
        
        // 拖拽结束
        element.addEventListener('dragend', (e) => {
            element.classList.remove('dragging');
            this.removeDragPlaceholder();
            this.draggedNode = null;
            this.dropTarget = null;
        });
        
        // 拖拽经过
        element.addEventListener('dragover', (e) => {
            if (!this.draggedNode || this.draggedNode === node) return;
            
            e.preventDefault();
            e.stopPropagation();
            e.dataTransfer.dropEffect = 'move';
            
            // 不能拖到自己的子节点
            if (this.draggedNode.isAncestorOf(node)) {
                e.dataTransfer.dropEffect = 'none';
                return;
            }
            
            this.dropTarget = node;
            this.showDragPlaceholder(element, e);
        });
        
        // 拖拽进入
        element.addEventListener('dragenter', (e) => {
            if (!this.draggedNode || this.draggedNode === node) return;
            e.preventDefault();
            element.style.background = 'rgba(33, 150, 243, 0.2)';
        });
        
        // 拖拽离开
        element.addEventListener('dragleave', (e) => {
            element.style.background = '';
        });
        
        // 放置
        element.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
            element.style.background = '';
            
            if (!this.draggedNode || !this.dropTarget) return;
            
            // 执行移动操作
            this.moveNodeTo(this.draggedNode.id, this.dropTarget.id);
            
            this.removeDragPlaceholder();
            this.draggedNode = null;
            this.dropTarget = null;
        });
    }
    
    /**
     * 显示拖拽占位符
     */
    showDragPlaceholder(element, event) {
        this.removeDragPlaceholder();
        
        const rect = element.getBoundingClientRect();
        const midpoint = rect.top + rect.height / 2;
        
        this.dragPlaceholder = document.createElement('div');
        this.dragPlaceholder.className = 'tree-drag-placeholder';
        
        // 如果拖到节点上半部分，显示在节点前
        if (event.clientY < midpoint) {
            element.parentElement.insertBefore(this.dragPlaceholder, element.parentElement);
        } else {
            // 否则显示在节点后
            element.parentElement.appendChild(this.dragPlaceholder);
        }
    }
    
    /**
     * 移除拖拽占位符
     */
    removeDragPlaceholder() {
        if (this.dragPlaceholder && this.dragPlaceholder.parentNode) {
            this.dragPlaceholder.parentNode.removeChild(this.dragPlaceholder);
            this.dragPlaceholder = null;
        }
    }
    
    /**
     * 移动节点到新父节点
     */
    moveNodeTo(nodeId, newParentId) {
        const success = this.treeManager.moveNode(nodeId, newParentId);
        
        if (success) {
            const node = this.treeManager.findNodeById(nodeId);
            const newParent = this.treeManager.findNodeById(newParentId);
            
            // 自动展开新父节点
            this.expandedNodes.add(newParentId);
            
            this.render();
            console.log(`✅ 已将节点 "${node.name}" 移动到 "${newParent.name}" 下`);
            
            // 通知后端保存
            this.notifyTreeChanged();
        }
    }
    
    /**
     * 添加子节点
     */
    addChildNode(parentId) {
        const parent = this.treeManager.findNodeById(parentId);
        if (!parent) return;
        
        // 提示用户输入节点名称
        const nodeName = prompt('请输入新节点名称:', '空节点');
        if (!nodeName || nodeName.trim() === '') return;
        
        // 创建一个空的 THREE.Group 作为容器
        const emptyGroup = new THREE.Group();
        emptyGroup.name = nodeName.trim();
        
        // 创建空节点
        const newNode = this.treeManager.addNode({
            name: nodeName.trim(),
            type: 'empty',
            object3D: emptyGroup,
            userData: { isEmpty: true }
        }, parentId);
        
        if (newNode) {
            // 自动展开父节点
            this.expandedNodes.add(parentId);
            
            this.render();
            this.selectNode(newNode.id);
            
            console.log(`✅ 已在 "${parent.name}" 下创建空节点 "${newNode.name}"`);
            
            // 通知后端保存
            this.notifyTreeChanged();
        }
    }
}

/**
 * 创建场景树UI实例
 * @param {HTMLElement} containerElement - 容器元素
 * @param {SceneTreeManager} treeManager - 树管理器
 * @param {string} mode - 显示模式 ('edit' 或 'presentation')
 */
export function createSceneTreeUI(containerElement, treeManager, mode = 'edit') {
    return new SceneTreeUI(containerElement, treeManager, mode);
}

